package com.op.teachingliteapp.sender.ui.view.thumbnailgallery;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.util.DensityUtils;
import org.vudroid.core.codec.CodecDocument;
import org.vudroid.pdfdroid.codec.PdfContext;


/**
 * Created by Genji on 2015/7/24.
 */
public class ThunbmailAdapter extends BaseAdapter {
    private Activity activity;
    private String url;
    private String TAG = this.getClass().getSimpleName();
    private CodecDocument pdfDocument;
    private int pageCount;
    private PdfContext pdfContext;
    private RectF rf;

    public ThunbmailAdapter(Activity activity, String url) {
        this.activity = activity;
        this.url = url;
        this.pdfContext = new PdfContext();
        this.pdfDocument = this.pdfContext.openDocument(this.url);
        this.pageCount = this.pdfDocument.getPageCount();
        this.rf = new RectF();
        this.rf.bottom = this.rf.right = (float) 1.0;
    }

    @Override
    public int getCount() {
        return this.pageCount;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(activity);
        View view = inflater.inflate(R.layout.item_thunbnail, null);
        TextView positon = (TextView) view.findViewById(R.id.thumbnail_positon);
        ImageView thumbailView = (ImageView) view.findViewById(R.id.thumbnail_view);


        thumbailView.setMinimumWidth(DensityUtils.dip2px(activity, 256));
        thumbailView.setMinimumHeight(DensityUtils.dip2px(activity, 256));
        positon.setText(String.valueOf(position+1));
        new ThumbnailLoader(thumbailView).execute(position);


        return view;
    }

    private class ThumbnailLoader extends AsyncTask<Integer, Bitmap, Void> {
        private ImageView imageView;

        public ThumbnailLoader(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        protected void onProgressUpdate(Bitmap... values) {
            this.imageView.setImageBitmap(values[0]);
        }

        @Override
        protected Void doInBackground(Integer... params) {
            Bitmap bitmap = pdfDocument.getPage(params[0]).renderBitmap(DensityUtils.dip2px(activity, 128), DensityUtils.dip2px(activity, 128), rf);
            publishProgress(bitmap);
            return null;
        }
    }


}
